<?php

namespace PHPSpring\Utils;

class Utils {

  public static function varToField($var): string {
    if (preg_match('/[A-Z]/', $var) === 0) {
      return $var;
    }

    return strtolower(preg_replace_callback('/([a-z])([A-Z])/', function ($a) {
      return $a[1]."_".strtolower($a[2]);
    }, $var));
  }

  public static function fieldToVar($field, $ucfirst = false): string {
    $str = str_replace('_', '', ucwords($field, '_'));
    if ($ucfirst) {
      return $str;
    }

    return lcfirst($str);
  }

  public static function typeToString ($type) {
    if (empty($type)) {
      return $type;
    }
    if (is_string($type)) {
      return $type;
    }
    if ($type instanceof \ReflectionNamedType) {
      return $type->getName();
    } elseif (version_compare(PHP_VERSION, '8.0', '>=') && ($type instanceof \ReflectionUnionType)) {
      $allTypes = $type->getTypes();
      return $allTypes[0]->getName();
    } else {
      throw new \InvalidArgumentException("Unrecognized type.");
    }
  }

  public static function isPrimaryType($type) {
    $type = self::typeToString($type);
    $type = $type ? trim($type, '?') : null;
    return ($type == null || in_array($type, array('int', 'bool', 'float', 'string', 'array')));
  }

  public static function normalizeReturnType ($type) {
    $retType = Utils::typeToString($type);
    if (!Utils::isPrimaryType($retType)) {
      $retType = '\\'.$retType;
    }
    return empty($retType) ? $retType : ': ' . $retType;
  }

  public static function normalizeParameterType ($type) {
    $ptype = Utils::typeToString($type);
    if (!Utils::isPrimaryType($ptype)) {
      $ptype = '\\'.$ptype;
    }
    return empty($ptype) ? $ptype : $ptype . ' ';
  }
}
